package com.mall.service.marketing.controller;

import com.mall.commons.common.CommonResult;
import com.mall.model.domain.SmsCoupon;
import com.mall.model.dto.SmsCouponDto;
import com.mall.model.vo.PageResult;
import com.mall.service.marketing.service.SmsCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/coupon")
public class SmsCouponController {

    @Autowired
    private SmsCouponService smsCouponService;

    /**
     * 根据优惠券名称和类型分页获取优惠券列表
     * @param name
     * @param type
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Cacheable(value = "coupuCache" ,key = "'coupuInfo'", unless = "#result.data==null")
    @GetMapping("/list")
    public CommonResult list(@RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "type", required = false) Integer type,
                             @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageResult pr = smsCouponService.list(name, type, pageNum, pageSize);
        return CommonResult.success(pr);
    }

    /**
     * 获取单个优惠券的详细信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public CommonResult findById(@PathVariable Integer id){
        SmsCoupon smsCoupon = smsCouponService.getById(id);
        return CommonResult.success(smsCoupon);
    }

    /**
     * 添加优惠券
     * @param smsCouponDto
     * @return
     */
    @PostMapping("/create")
    @CacheEvict(value = "coupuCache", allEntries = true)
    public CommonResult create(@RequestBody SmsCouponDto smsCouponDto){
        Integer count = smsCouponService.create(smsCouponDto);
        if (count > 0) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.success("添加失败");
    }

    /**
     * 删除优惠券
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    @CacheEvict(value = "coupuCache", allEntries = true)
    public CommonResult delete(@PathVariable Integer id){
        Integer count = smsCouponService.delete(id);
        if (count > 0) {
            return CommonResult.success("删除成功");
        }
        return CommonResult.success("删除失败");
    }

    /**
     * 修改优惠券
     * @param id
     * @return
     */
    @PostMapping("/update/{id}")
    @CacheEvict(value = "coupuCache", allEntries = true)
    public CommonResult update(@PathVariable Long id, @RequestBody SmsCouponDto smsCouponDto){
        Integer count = smsCouponService.update(id, smsCouponDto);
        if (count > 0) {
            return CommonResult.success("修改成功");
        }
        return CommonResult.success("修改失败");
    }
}
